﻿using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Entities;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine;

public class CharacterSpawner : MonoBehaviour
{
#pragma warning disable CS0649
    [SerializeField] private GameObject characterPrefab;
    [SerializeField] private float characterMoveSpeed;
#pragma warning restore CS0649

    private Entity characterEntityPrefab;
    private EntityManager entityManager;

    private BlobAssetStore blobAssetStore;

    public void Initialize()
    {
        InitializeData();
        InitializePrefab();
        SpawnCharacter();
    }

    public void Uninitialize() => CleanUp();

    private void InitializePrefab()
    {
        blobAssetStore = new BlobAssetStore();
        var settings = GameObjectConversionSettings.FromWorld(GlobalContext.GetWorld(), blobAssetStore);
        characterEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(characterPrefab, settings);
    }

    private void InitializeData()
    {
        entityManager = GlobalContext.GetEntityManager();
    }

    private void SpawnCharacter()
    {
        EntityArchetype archetype = entityManager.CreateArchetype(
            typeof(Translation),    // 位置
            typeof(Rotation),       // 旋转
            typeof(RenderMesh),     // 渲染
            typeof(LocalToWorld),
            typeof(PlayerInputData),
            //typeof(MovementData),
            typeof(CharacterTag)    // 标签
            );

        Entity entity = entityManager.Instantiate(characterEntityPrefab);
        //Debug.Log(entity.Index);
        entityManager.SetArchetype(entity, archetype);

        //entityManager.SetComponentData<PlayerInputData>(entity, new PlayerInputData() { MoveX = 0, MoveY = 0 });
        entityManager.AddComponentData<MovementData>(entity, new MovementData() { MoveSpeed = characterMoveSpeed });
    }

    private void CleanUp()
    {
        blobAssetStore.ResetCache(true);
        blobAssetStore.Dispose();
    }
}
